/**
 * 	author wanghua
 */

if(!window.console){
	window.console={};
	window.console.log=function(){return;};
}

/**全局处理异常
 * author wanghua
 * */
window.onerror = function(){
	if(typeof(window.dkDialog_closeLoading) == 'function'){
		window.dkDialog_closeLoading();	//关闭loading窗口	
	}
}

/**执行函数 fun
 * @param funName 函数名的字符串。比如正确写法为： common_apply("onSelect", {}, "");
 * @param param 参数 fun执行时的参数,多个参数用数组
 * @param defaultResult 当 fun 不存在的时候的返回值
 * @param funcDefStr 函数不存在时的提示信息，一般为函数的名称和参数形式，比如 "onSelect(index){}"
 * @returns
 */
var common_js_apply = function(funName, param, defaultResult, funcDefStr){
	try{
		var fun = this[funName];
		if (typeof(fun) == "function") {
			return fun.apply(this,param);
		}else {
			if(!funcDefStr) funcDefStr = funName;
			console.log("函数："+funcDefStr+" 没有定义,可以在页面的js文件中查看对此函数的调用");
			return defaultResult;
		}
	}catch(e){

	}
};

/**wanghua
窗口大小改变时，对页面元素重新布局。
安装上 、中（左中右）、下的方式布局
5个div的id分布如下；
#topPanel
#leftPanel
#rightPanel
#mainPanel
#bottomPanel

options:{
	onResized : function(){},
}
*/
function common_js_layout(){
	this.init = function(options){
		var self = this;
		self.options = options;
		$(document.body).css({
			"overflow-x":"hidden", //禁用滚动条。否则resize时，计算的窗口大小不准确
			"overflow-y":"hidden"
		});
		this.resizeLayout();
		$(window).resize(function() {
			self.resizeLayout();
			//setTimeout(function(){alert('relayout');self.resizeLayout();},10);
		});
		return this;
	};

	/** x, y, width, height都是正整数,其中width，height包含了padding和margin*/
	this.setPositionAndSize = function (id, x, y, outerWidth, outerHeight){
		if(id[0] != '#') id = '#'+id;
		var jqElement = $(id);

		var marginLeft = parseInt(jqElement.css('marginLeft'));
		var marginRight = parseInt(jqElement.css('marginRight'));
		var paddingLeft = parseInt(jqElement.css('paddingLeft'));
		var paddingRight = parseInt(jqElement.css('paddingRight'));
		var borderLeft = parseInt(jqElement.css('borderLeftWidth'));
		var borderRight = parseInt(jqElement.css('borderRightWidth'));

		var marginTop = parseInt(jqElement.css('marginTop'));
		var marginBottom = parseInt(jqElement.css('marginBottom'));
		var paddingTop = parseInt(jqElement.css('paddingTop'));
		var paddingBottom = parseInt(jqElement.css('paddingBottom'));
		var borderTop = parseInt(jqElement.css('borderTopWidth'));
		var borderBottom = parseInt(jqElement.css('borderBottomWidth'));

		var width = outerWidth - marginLeft - marginRight- paddingLeft - paddingRight- borderLeft - borderRight;
		var height = outerHeight - marginTop - marginBottom - paddingTop - paddingBottom - borderTop - borderBottom;

		jqElement.css("position", "absolute");
		jqElement.css("left", x+"px");
		jqElement.css("top", y+"px");
		jqElement.width(width);
		jqElement.height(height);
	};

	this.resizeLayout = function(){
		var self = this;
		var clientHeight = $(window).height();
		var clientWidth = $(window).width();
		var topHeight = $("#topPanel").outerHeight(true) || 0;//40; //logo band 的高度
		if($("#topPanel").css("display") == "none") topHeight = 0;

		var leftWidth = $("#leftPanel").outerWidth(true) || 0;//左侧边栏的宽度
		if($("#leftPanel").css("display") == "none") leftWidth = 0;

		var rightWidth= $("#rightPanel").outerWidth(true) || 0;//右侧边栏的宽度
		if($("#rightPanel").css("display") == "none") rightWidth = 0;

		var bottomHeight = $("#bottomPanel").outerHeight(true) || 0; //底部copyright的高度
		if($("#bottomPanel").css("display") == "none") bottomHeight = 0;

		var mainHeight = clientHeight - topHeight - bottomHeight;
		var mainWidth = clientWidth - leftWidth - rightWidth;
		var mainX = leftWidth;
		var mainY = topHeight;
		var leftY = topHeight;
		var leftHeight = mainHeight + bottomHeight;
		var rightHeight = mainHeight + bottomHeight;
		var rightX = leftWidth + mainWidth;
		var rightY = topHeight;
		var bottomY = topHeight + mainHeight;

		this.setPositionAndSize("#topPanel", 0, 0, clientWidth, topHeight);
		this.setPositionAndSize("#leftPanel", 0, leftY, leftWidth, leftHeight);
		this.setPositionAndSize("#rightPanel", rightX, rightY, rightWidth, rightHeight);
		this.setPositionAndSize("#mainPanel", mainX, mainY, mainWidth, mainHeight);
		this.setPositionAndSize("#bottomPanel", mainX, bottomY, mainWidth , bottomHeight);

		if(self.options && self.options.onResized){
			self.options.onResized();
		}
	};
}

jQuery.extend({
	  /**
	    * 同步的Post请求
	   */
	syncGetJSON:function(url, data, method){
		if(method && method.toUpperCase() == "POST" ){
			method = "POST";
		}else{
			method = "GET";
		}

		var resultData;
		$.ajax({
			async : false,
			type: method,
			url: url,
			data: data,
			dataType: "json"
		}).done(function (data){
			resultData = data;
		});
		return resultData;
	},

	syncPost:function(url, data, func){
		var funcResult;
		var resultData;
		$.ajax({
			async : false,
			type: "POST",
			url: url,
			data: data,
			dataType: "json"
		}).done(function (data){
			resultData = data;
			if(func instanceof Function) funcResult = func(data);
		});
		if(func instanceof Function) return funcResult;
		return resultData;
	}
});

function JavaScriptEncode(str){
    
    var hex=new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
        
    function changeTo16Hex(charCode){
        return "\\x" + charCode.charCodeAt(0).toString(16);
    }
    
    function encodeCharx(original) {
        
        var found = true;
        var thecharchar = original.charAt(0);
        var thechar = original.charCodeAt(0);
        switch(thecharchar) {
            case '\n': return "\\n"; break; //newline
            case '\r': return "\\r"; break; //Carriage return
            case '\'': return "\\'"; break;
            case '"': return "\\\""; break;
            case '\&': return "\\&"; break;
            case '\\': return "\\\\"; break;
            case '\t': return "\\t"; break;
            case '\b': return "\\b"; break;
            case '\f': return "\\f"; break;
            case '/': return "\\x2F"; break;
            case '<': return "\\x3C"; break;
            case '>': return "\\x3E"; break;
            default:
                found=false;
                break;
        }
        if(!found){
            if(thechar > 47 && thechar < 58){ //数字
                return original;
            }
            
            if(thechar > 64 && thechar < 91){ //大写字母
                return original;
            }

            if(thechar > 96 && thechar < 123){ //小写字母
                return original;
            }        
            
            if(thechar>127) { //大于127用unicode
                var c = thechar;
                var a4 = c%16;
                c = Math.floor(c/16); 
                var a3 = c%16;
                c = Math.floor(c/16);
                var a2 = c%16;
                c = Math.floor(c/16);
                var a1 = c%16;
                return "\\u"+hex[a1]+hex[a2]+hex[a3]+hex[a4]+"";        
            }
            else {
                return changeTo16Hex(original);
            }
            
        }
    }     
  
    var preescape = str;
    var escaped = "";
    var i=0;
    if(preescape){
    for(i=0; i < preescape.length; i++){
        escaped = escaped + encodeCharx(preescape.charAt(i));
    }
    }
    return escaped;
}

/**将文本中的一般的HTML特殊字符进行转换*/
function escapeHtml(string) {
    var entityMap = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
    };
    return String(string).replace(/[&<>"'\/]/g, function (s) {
        return entityMap[s];
    });
}
/**将文本中的HTML特殊字符进行转换*/
function HtmlEncode(str){	
	if(typeof(str) != 'string')return str;	
	if(!str||str == 'null')return '';
    var hex = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
    var preescape = "" + str;
    var escaped = "";
    for(var i = 0; i < preescape.length; i++){
        var p = preescape.charAt(i);
        escaped = escaped + escapeCharx(p);
    }
    
    return escaped;
                    
    function escapeCharx(original){
        var found=true;
        var thechar=original.charCodeAt(0);
        switch(thechar) {
            case 10: return "<br/>"; break; //newline
            case 32: return "&nbsp;"; break; //space
            case 34:return "&quot;"; break; //"
            case 38:return "&amp;"; break; //&
            case 39:return "&#x27;"; break; //'
            case 47:return "&#x2F;"; break; // /
            case 60:return "&lt;"; break; //<
            case 62:return "&gt;"; break; //>
            case 198:return "&AElig;"; break;
            case 193:return "&Aacute;"; break;
            case 194:return "&Acirc;"; break; 
            case 192:return "&Agrave;"; break; 
            case 197:return "&Aring;"; break; 
            case 195:return "&Atilde;"; break; 
            case 196:return "&Auml;"; break; 
            case 199:return "&Ccedil;"; break; 
            case 208:return "&ETH;"; break;
            case 201:return "&Eacute;"; break; 
            case 202:return "&Ecirc;"; break; 
            case 200:return "&Egrave;"; break; 
            case 203:return "&Euml;"; break;
            case 205:return "&Iacute;"; break;
            case 206:return "&Icirc;"; break; 
            case 204:return "&Igrave;"; break; 
            case 207:return "&Iuml;"; break;
            case 209:return "&Ntilde;"; break; 
            case 211:return "&Oacute;"; break;
            case 212:return "&Ocirc;"; break; 
            case 210:return "&Ograve;"; break; 
            case 216:return "&Oslash;"; break; 
            case 213:return "&Otilde;"; break; 
            case 214:return "&Ouml;"; break;
            case 222:return "&THORN;"; break; 
            case 218:return "&Uacute;"; break; 
            case 219:return "&Ucirc;"; break; 
            case 217:return "&Ugrave;"; break; 
            case 220:return "&Uuml;"; break; 
            case 221:return "&Yacute;"; break;
            case 225:return "&aacute;"; break; 
            case 226:return "&acirc;"; break; 
            case 230:return "&aelig;"; break; 
            case 224:return "&agrave;"; break; 
            case 229:return "&aring;"; break; 
            case 227:return "&atilde;"; break; 
            case 228:return "&auml;"; break; 
            case 231:return "&ccedil;"; break; 
            case 233:return "&eacute;"; break;
            case 234:return "&ecirc;"; break; 
            case 232:return "&egrave;"; break; 
            case 240:return "&eth;"; break; 
            case 235:return "&euml;"; break; 
            case 237:return "&iacute;"; break; 
            case 238:return "&icirc;"; break; 
            case 236:return "&igrave;"; break; 
            case 239:return "&iuml;"; break; 
            case 241:return "&ntilde;"; break; 
            case 243:return "&oacute;"; break;
            case 244:return "&ocirc;"; break; 
            case 242:return "&ograve;"; break; 
            case 248:return "&oslash;"; break; 
            case 245:return "&otilde;"; break;
            case 246:return "&ouml;"; break; 
            case 223:return "&szlig;"; break; 
            case 254:return "&thorn;"; break; 
            case 250:return "&uacute;"; break; 
            case 251:return "&ucirc;"; break; 
            case 249:return "&ugrave;"; break; 
            case 252:return "&uuml;"; break; 
            case 253:return "&yacute;"; break; 
            case 255:return "&yuml;"; break;
            case 162:return "&cent;"; break; 
            case '\r': break;
            default:
                found=false;
                break;
        }
        if(!found){
            if(thechar>127) {
                var c=thechar;
                var a4=c%16;
                c=Math.floor(c/16); 
                var a3=c%16;
                c=Math.floor(c/16);
                var a2=c%16;
                c=Math.floor(c/16);
                var a1=c%16;
                return "&#x"+hex[a1]+hex[a2]+hex[a3]+hex[a4]+";";        
            }
            else{
                return original;
            }
        }    
    }
}
/*hideButtonnId为需要隐藏的按钮id,可以是单个ID字符串，也可以是Id数组，或者为空*/
function htmlPrint(hideButtonId){
	var orgHtml=window.document.body.innerHTML;//原页面
    //修改边框颜色
    $(".table-bordered tbody tr td").each(function (index ,val) {
	      $(val)[0].style.cssText='border:1px solid #000!important;';
    });
    if(typeof(hideButtonId)=="string")
    {
    	$("#"+hideButtonId).hide();//隐藏按钮
	    window.print();
	    $("#"+hideButtonId).show();//显示按钮
    }else if(typeof(hideButtonId)=="object")
    {
    	if(hideButtonId)
    	{
    		for(var i=0;i<hideButtonId.length;i++)
    		{
    			$("#"+hideButtonId[i]).hide();//隐藏按钮
    		}	
    		window.print();
   		    for(var i=0;i<hideButtonId.length;i++)
   			{
   				$("#"+hideButtonId).show();//显示按钮
   			}
    	}    	
    }
    else{
    	 window.print();
    }
	window.document.body.innerHTML=orgHtml; // 最后还原页面
}

/**common.js**/
String.prototype.endsWith=function(endStr){
    var d=this.length-endStr.length;
    return (d>=0&&this.lastIndexOf(endStr)==d)
}
